/** 
  成绩录入开关
*/
<template>
  <div class="score-entry-switch-container">
    <!-- 成绩录入开关列表页开始 -->
    <div v-if="indexKey === 0">
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('scoreEntrySwitch.scoreEntrySwitch')}}</h1>
        <div class="float-right" style="margin-bottom:24px;">
          <el-button v-if="permitToDelete" type="danger" @click="deleteData()">{{ $t('common.btn.delete') }}</el-button>
          <el-button v-if="permitToAdd" type="primary" @click="addData()">{{ $t('common.btn.add') }}</el-button>
        </div>
        <edu-table 
          ref="scoreEntrySwitch" 
          :selection="true"
          :pagination="false" 
          :order='false' 
          tooltipEffect="light" 
          stripe 
          :data="dataList" 
          size="mini"
          @selection-change="handleSelectionChange">
          <el-table-column type="expand">
            <template slot-scope="props">
              <div class="expand-header">
                <el-row :gutter="24">
                  <el-col
                    :span="2"
                    style="text-align: right; padding: 0;color:#99a9bf;">
                    <span>{{ $t('scoreEntrySwitch.semester') + '：' }}</span>
                  </el-col>
                  <el-col :span="6">
                    <span>{{ props.row.calendar }}</span>
                  </el-col>
                  <el-col
                    :span="2"
                    style="text-align: right; padding: 0;color:#99a9bf;">
                    <span>{{ $t('scoreEntrySwitch.startTime') + '：' }}</span>
                  </el-col>
                  <el-col :span="6">
                    <span>{{ getTime(props.row.startTime) }}</span>
                  </el-col>
                  <el-col
                    :span="2"
                    style="text-align: right; padding: 0;color:#99a9bf;">
                    <span>{{ $t('scoreEntrySwitch.endTime') + '：' }}</span>
                  </el-col>
                  <el-col :span="6">
                    <span>{{ getTime(props.row.stopTime) }}</span>
                  </el-col>
                </el-row>
              </div>
              <div v-if="props.row.facultyCnArry.length > 0" class="expand-header">
                <el-row :gutter="24">
                  <el-col
                    :span="2"
                    style="text-align: right; padding: 0; color:#99a9bf">
                    <span>{{ $t("scoreEntrySwitch.startCollege") + '：' }}</span>
                  </el-col>
                  <el-col :span="22" style="padding: 0;">
                    <el-col
                      v-for="(item, index) in props.row.facultyCnArry"
                      :span="6"
                      :key="index"
                      style="height: 24px;">
                      <span>{{ ++index + '.' + item }}</span>
                    </el-col>
                  </el-col>
                </el-row>
              </div>
              <div class="expand-header" v-if="props.row.inputTypeDetails">
                <el-row :gutter="24">
                  <el-col :span="2" style="text-align: right; padding: 0; color:#99a9bf">
                    <span>{{ $t("scoreEntrySwitch.enteredTypes") + '：' }}</span>
                  </el-col>
                  <el-col :span="22">
                    {{ props.row.inputTypeDetails }}
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('scoreEntrySwitch.semester')" prop="calendar"></el-table-column>
          <el-table-column :label="$t('scoreEntrySwitch.startCollege')" prop="facultyCns"></el-table-column>
          <el-table-column :label="$t('scoreEntrySwitch.startTime')" prop="startTime">
              <template slot-scope="scope">{{ getTime(scope.row.startTime) }}</template>
          </el-table-column>
          <el-table-column :label="$t('scoreEntrySwitch.endTime')" prop="stopTime">
              <template slot-scope="scope">{{ getTime(scope.row.stopTime) }}</template>
          </el-table-column>
          <el-table-column :label="$t('score.studebtScoreQueryForLeave.opertion')" width="200px">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="editScoreRecordOpen(scope.row)">
                {{ $t('common.btn.edit') }}
              </el-button>
              <el-button
                type="text"
                @click="deleteScoreRecordOpen(scope.row)">
                {{ $t('common.btn.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </edu-table >
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 成绩录入开关列表页结束 -->
    <!-- 新增权限开始 -->
    <div v-if="indexKey === 1">
      <add-score-entry-switch @score-manage-reset-index-key="resetIndexKey"></add-score-entry-switch>
    </div>
    <!-- 新增权限结束 -->
    <!-- 编辑权限开始 -->
    <div v-if="indexKey === 2">
      <edit-score-entry-switch :detailInfo="detailInfo" @score-manage-reset-index-key="resetIndexKey"></edit-score-entry-switch>
    </div>
    <!-- 编辑权限结束 -->
  </div>
</template>
<script>
import UTILS from "common/src/utils/utils";
import filters from "common/src/filters";
import { queryDic } from "common/src/api/dictionary";
import scoreManagementApi from 'common/src/api/scoreManagement/scoreManagement';
import addScoreEntrySwitch from './addScoreEntrySwitch';
import editScoreEntrySwitch from './editScoreEntrySwitch';
import * as INDEX from 'common/src/utils/index';
export default {
  components: {
    'add-score-entry-switch': addScoreEntrySwitch,
    'edit-score-entry-switch': editScoreEntrySwitch
  },
  data () {
    return {
      indexKey: 0,
      auths: [],
      userInfo: {},
      permitToAdd: false,
      permitToDelete: false,
      permitToEdit: false,
      permitToSelect: false,
      queryForm: {
        "calendarId": "",
        "pageNum_": 1,
        "pageSize_": 20,
        "total_": 0
      },
      options: {
        gradeNameCn: [],
        finalGrade: [],
        totalGrade: [],
        publishGrade: [],
        withoutGrade: [],
        allowResetExam: []
      },
      dataList: [],
      multipleSelection: [],
      detailInfo: {}
    }
  },
  filters: {
    
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
      if (JSON.parse(localStorage.getItem("sessiondata")).mockUser) {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).mockUser
      } else {
        this.userInfo = JSON.parse(localStorage.getItem("sessiondata")).user
      }
    }
    this.onSubmit()
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    // 校验及格线，最多6位数，最多保留2位小数点，最大100
    validateGradePassLine(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/;
      if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')))
      } else if (Number(value) === 0 || Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')));
      } else {
        callback();
      }
    },
    // 校验最小值，最多6位数，最多保留2位小数点，最大100
    validateScoreMin(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error(this.$t('gradeRelatedSetting.requireScoreMin')));
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')))
      } else if (Number(value) === 0 || Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')));
      } else {
        callback();
      }
    },
    // 校验最大值，最多6位数，最多保留2位小数点，最大100
    validateScoreMax(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error(this.$t('gradeRelatedSetting.requireScoreMax')));
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')))
      } else if (Number(value) === 0 || Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')));
      } else {
        callback();
      }
    },
    // 校验默认值，最多6位数，最多保留2位小数点，最大100
    validateScoreDefault(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error(this.$t('gradeRelatedSetting.requireScoreDefault')));
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')))
      } else if (Number(value) === 0 || Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.validateScore')));
      } else {
        callback();
      }
    },
    // 校验绩点，最多5位数，最多保留1位小数点，最大100
    validateGradePoint(rule, value, callback) {
      let expReg = /^(\d{1,3})(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error(this.$t('gradeRelatedSetting.requireGradePoint')));
      } else if (!expReg.test(value)) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGradePoint')))
      } else if (Number(value) === 0 || Number(value) > 100) {
        callback(new Error(this.$t('gradeRelatedSetting.validateGradePoint')));
      } else {
        callback();
      }
    },
    // 重置首页
    resetIndexKey() {
      this.indexKey = 0
      this.multipleSelection = []
      this.onSubmit()
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    getListData() {
      scoreManagementApi.getGradeRightSwitchList(this.queryForm).then((res) => {
        this.dataList = res.data.list
        this.queryForm.total_ = res.data.total
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    },
    reset() {
      this.baseLevel = []
      Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '')
      this.onSubmit()
    },
    // 获取时间
    getTime(timeStamp) {
      return INDEX.parseTime(new Date(timeStamp), '{y}/{m}/{d} {h}:{i}:{s}')
    },
    // 删除
    deleteData() {
      if (this.multipleSelection.length > 0) {
        let deleteArray = []
        this.multipleSelection.map(value => {
          deleteArray.push(value.id)
        })
        this.$delConfirm().then(_ => {
          scoreManagementApi.deleteScoreEntrySwitch(deleteArray.join(',')).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success', 
                message: this.$t('scoreMangementBase.deleteSuccessfully')
              })
              this.onSubmit();
            }
          })
        })
      } else {
        this.$message(this.$t('graduateBase.pleaseChoose'));
      }
    },
    // 新增权限
    addData() {
      this.indexKey = 1
    },
    // 确定
    confirm() {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          let gradeNameCnArr = this.options.gradeNameCn.filter(value => {
            return value.value === this.dialogForm.gradeNameCn 
          })
          let params = {
            "gradeNameCode": this.dialogForm.gradeNameCn,
            "gradeNameCn": gradeNameCnArr[0].label,
            "gradeNameEn": this.dialogForm.gradeNameEn,
            "gradePassLine": this.dialogForm.gradePassLine,
            "manageDeptId": this.userInfo.currentManageDptId,
            "minorGradeRelatedSetDetailsList": this.dialogForm.minorGradeRelatedSetDetailsList
          }
          if (this.dialogMode === 'add') {
            if (this.dialogForm.hasOwnProperty('gradeSetId')) {
              delete this.dialogForm.gradeSetId
            }
            scoreManagementApi.addScoreRecordMethod(params).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success', 
                  message: this.$t('scoreMangementBase.addSuccessfully')
                })
                this.cancel()
                this.onSubmit()
              }
            })
          } else if (this.dialogMode === 'edit') {
            params['gradeSetId'] = this.dialogForm.gradeSetId
            scoreManagementApi.editScoreRecordMethod(params).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success', 
                  message: this.$t('scoreMangementBase.editSuccessfully')
                })
                this.cancel()
                this.onSubmit()
              }
            })
          }
          
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus();
            }
          }, 1);
        }
      })
    },
    // 编辑
    editScoreRecordOpen(row) {
      this.detailInfo = row
      this.indexKey = 2
    },
    // 删除
    deleteScoreRecordOpen(row) {
      this.$delConfirm().then(_ => {
        scoreManagementApi.deleteScoreEntrySwitch(row.id).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success', 
              message: this.$t('scoreMangementBase.deleteSuccessfully')
            })
            this.onSubmit();
          }
        })
      })
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'scoremanage-ralatedSetting-add') {
              this.permitToAdd = true
            }
            if (item.authCode === 'scoremanage-ralatedSetting-edit') {
              this.permitToDelete = true
            }
            if (item.authCode === 'scoremanage-ralatedSetting-delete') {
              this.permitToEdit = true
            }
            if (item.authCode === 'scoremanage-ralatedSetting-select') {
              this.permitToSelect = true
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .score-entry-switch-container ::v-deep {
    .expand-header {
      height: 32px;
    }
    .el-dialog__body {
      word-break: break-all!important
    }
  }
</style>
